<!DOCTYPE html>
<html lang="zh-CN">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>循环队列指针判断</title>
  <style>
    .box {
      width: 50px;
      height: 50px;
      display: inline-block;
      border: 1px solid black;
      text-align: center;
      line-height: 50px;
      margin: 5px;
      font-size: 18px;
    }
    .controls, .result {
      margin-top: 20px;
    }
  </style>
</head>
<body>
<h2>循环队列指针判断</h2>
<div id="queue-container"></div>
<div class="controls">
  <button onclick="insert()">插入</button>
  <button onclick="remove()">删除</button>
  <button onclick="submitAnswer()">确认头尾位置</button>
</div>
<div class="result" id="result"></div>

<script>
  // 随机生成 n 和 x
  const n = Math.floor(Math.random() * 5) + 6;
  const x = Math.floor(Math.random() * n);
  let queue = Array(n).fill(null);
  let front = 0;
  let rear = x - 1;
  let operations = 0;

  // 填充初始数据
  for (let i = 0; i < x; i++) {
    queue[i] = Math.floor(Math.random() * 100) + 1;
  }

  function renderQueue() {
    const container = document.getElementById("queue-container");
    container.innerHTML = "";
    queue.forEach((value, index) => {
      const box = document.createElement("div");
      box.className = "box";
      box.style.backgroundColor = index === front ? 'lightgreen' : (index === rear ? 'lightcoral' : '');
      box.innerText = value === null ? "" : value;
      container.appendChild(box);
    });
  }

  function insert() {
    if (operations >= 4) {
      alert("已达到最大操作次数");
      return;
    }
    if (queue[(rear + 1) % n] === null) {
      rear = (rear + 1) % n;
      queue[rear] = Math.floor(Math.random() * 100) + 1;
      operations++;
      renderQueue();
    } else {
      alert("队列已满，无法插入");
    }
  }

  function remove() {
    if (operations >= 4) {
      alert("已达到最大操作次数");
      return;
    }
    if (queue[front] !== null) {
      queue[front] = null;
      front = (front + 1) % n;
      operations++;
      renderQueue();
    } else {
      alert("队列为空，无法删除");
    }
  }

  function submitAnswer() {
    const userFront = prompt("请输入您认为的头指针位置 (0 到 " + (n - 1) + "):");
    const userRear = prompt("请输入您认为的尾指针位置 (0 到 " + (n - 1) + "):");

    if (parseInt(userFront) === front && parseInt(userRear) === rear) {
      document.getElementById("result").innerText = "正确！头尾指针位置正确。";
    } else {
      document.getElementById("result").innerText = "错误。实际头指针在位置 " + front + "，尾指针在位置 " + rear + "。";
    }
  }

  renderQueue();
</script>
</body>
</html>
